package com.rui.mq.rocketmq.transaction;

import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.producer.*;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.concurrent.TimeUnit;

public class Producer {

    public static void main(String[] args) throws Exception{
        TransactionMQProducer producer = new TransactionMQProducer("groups");
        producer.setNamesrvAddr("192.168.10.129:9876;192.168.10.129:9877");
        producer.setVipChannelEnabled(false);
        producer.setSendMsgTimeout(10000);
        producer.setTransactionListener(new TransactionListener() {
            @Override
            public LocalTransactionState executeLocalTransaction(Message message, Object o) {
                if(StringUtils.equals("TAGA",message.getTags())){
                    return LocalTransactionState.COMMIT_MESSAGE;
                }else if(StringUtils.equals("TAGB",message.getTags())){
                    return LocalTransactionState.ROLLBACK_MESSAGE;
                }else if(StringUtils.equals("TAGC",message.getTags())){
                    return LocalTransactionState.UNKNOW;
                }else {
                    return LocalTransactionState.UNKNOW;
                }
            }

            @Override
            public LocalTransactionState checkLocalTransaction(MessageExt messageExt) {
                System.out.println("消息的Tag：" + messageExt.getTags());
                return LocalTransactionState.COMMIT_MESSAGE;
            }
        });
        producer.start();
        String[] tags = {"TAGA","TAGB","TAGC"};
        for (int i = 0; i < 3; i++) {
            Message msg = new Message("TransactionTopic",tags[i],("Hello World" + i).getBytes());
            TransactionSendResult result = producer.sendMessageInTransaction(msg, null);
            System.out.println("发送结果：" + result);
            TimeUnit.SECONDS.sleep(1);
        }
//        producer.shutdown();
    }
}
